package com.sodaopen.crm.utils;

import java.util.Date;
import java.util.Map;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtil {
	/**
	 * 过期24小时
	 */
//	private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
	private static final long EXPIRE_TIME = 60 * 60 * 1000;
	/**
	 * jwt密钥
	 */
	private static final String SECRET = "xzcrm_jwt_key#abc";

	/**
	 * 生成签名
	 */
	public static String createJwt(String id, String username, Map<String, Object> claims) {
		Date now = new Date();
		Date expiredDate = new Date(now.getTime() + EXPIRE_TIME);
		
		JwtBuilder builder =  Jwts.builder()
								.setId(id)
								.setSubject(username)
								.setIssuedAt(now)
								.setExpiration(expiredDate)
								.signWith(SignatureAlgorithm.HS256, SECRET);
		
		for(String key : claims.keySet()) {
			builder.claim(key, claims.get(key));
		}
		
		return builder.compact();
	}

	/**
	 * 根据token获取userId
	 * 
	 * @param token
	 * @return
	 */
	public static Claims parseJwt(String token) {
		Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
		return claims;
	}

}
